package com.example.code.class03;

import java.util.Arrays;

/**
 * @Date 2022/7/17
 * @Created by Jonathan
 */
public class Code04_MaxPairNumber {
    public static void main(String[] args) {
        int[] arr = {3, 1, 3, 1, 5, 7};
        System.out.println(maxPairNum(arr, 2));
    }

    private static int maxPairNum(int[] arr, int k) {
        // 排序
        Arrays.sort(arr);
        int ans = 0;
        int N = arr.length;
        int L = 0;
        int R = 0;
        boolean[] usedR = new boolean[N];
        while (L < N && R < N) {
            if (usedR[L]) {
                L++;
            } else if (L >= R) {
                R++;
            } else {
                int distance = arr[R] - arr[L];
                if (distance == k) {
                    ans++;
                    usedR[R++] = true;
                    L++;
                } else if (distance < k) {
                    R++;
                } else {
                    L++;
                }
            }
        }
        return ans;
    }
}
